package cn.xzqwjw.taskmanager.common.converter;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import cn.xzqwjw.taskmanager.common.customEnum.ResponseCodeEnum;
import cn.xzqwjw.taskmanager.common.exception.CustomException;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 自定义反序列化 LocalDate
 *
 * @author rush
 */
public class CustomLocalDateDeserializer extends JsonDeserializer<LocalDate> {

  @Override
  public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    long timestamp = parser.getValueAsLong();
    if (timestamp > 0) {
      return LocalDate.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
    }
    String dtString = parser.getText().trim();
    if (!StringUtils.hasLength(dtString)) {
      return null;
    }
    try {
      DateTimeFormatter formatter;
      if (dtString.length() == 10 && dtString.charAt(4) == '-' && dtString.charAt(7) == '-') {
        formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
      } else if (dtString.length() == 10 && dtString.charAt(4) == '/' && dtString.charAt(7) == '/') {
        formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
      } else {
        throw new CustomException(ResponseCodeEnum.PARSE_DATE_ERROR);
      }
      // 时区修正 return LocalDate.parse(dtString, formatter).plusHours(8);
      return LocalDate.parse(dtString, formatter);
    } catch (DateTimeParseException ex) {
      throw new CustomException(ResponseCodeEnum.PARSE_DATE_ERROR);
    }
  }

}
